﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class FoldersViewEN : System.Web.UI.Page
{

    public List<Folders> lstGridFolders
    {
        get
        {
            if (ViewState["lstGridFolders"] == null)
            {
                ViewState["lstGridFolders"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstGridFolders"].ToString()] == null)
            {
                Session[ViewState["lstGridFolders"].ToString()] = new List<Folders>();

            }

            return (List<Folders>)Session[ViewState["lstGridFolders"].ToString()];

        }
        set
        {
            if (ViewState["lstGridFolders"] == null)
            {
                ViewState["lstGridFolders"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstGridFolders"].ToString()] = value;
        }   
   
   

    }


    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);
       
        if (!Page.IsPostBack)
        {
            bindGrid("");
            bindTree();
        }

    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {
        
        List<Folders> lstFolders = search (strIn);

        

        lstGridFolders = lstFolders;

        grdUsers.DataSource = lstFolders;
        grdUsers.DataBind();
    }


    protected void bindTree()
    {
        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);

        List<Folders> lstFolders = objFoldersDB.Select("", " where [ParentID] is NULL OR [ParentID] = '-1' ");

        FoldersHierList lstFoldersHier = new FoldersHierList(lstFolders);

        trFolders.DataSource = lstFoldersHier;
        trFolders.DataBind();
        trFolders.CollapseAll();

    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Folders_page))
            Response.Redirect("LoginEN.aspx");



       




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);
       
    }

    /// <summary>
    /// this function will search in folders and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of folders matched</returns>
    protected List<Folders> search(string txtText)
    {
        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
        List<Folders> lstRet = new List<Folders>();
        if (txtText.Trim() == "")
        {
            List<Folders> lstNew = objFoldersDB.Select (" top 100 "," order by [FolderNameEN] " );
            //lstNew = new List<Folders>(from objFol in lstNew where objFol.StatusID != 2 select objFol );
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            Folders objFolders = new Folders();
            objFolders.FolderNameAR = objFolders.FolderNameEN = "%" + strValue + "%";
            List<Folders> lstFolders = objFoldersDB.SearchOrLike(objFolders);
            //lstFolders = new List<Folders>(from objFol in lstFolders where objFol.StatusID != 2 select objFol);

            foreach (Folders objFol in lstFolders)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_folders_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long FolderID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
        List<Folders> lstFolders = objFoldersDB.getFoldersByID (FolderID);




        if (lstFolders.Count == 0)
        {
            lblError.Text = "No Folders to delete";
            lblResult.Text = "";
            return;
        }





        //if (lstFolders[0].lstChild.Count > 0 || lstFolders[0].lstCourses.Count > 0)
        //{
            bool bRet = objFoldersDB.deleteAll(lstFolders[0]);
            if (bRet)
            {
                lblResult.Text = "Deleted ok.";
                bindGrid(txtSearch.Text);
            }
            else
            {
                lblError.Text = "Error Deleting.";
            }
            return;
        //}


        //objFoldersDB.Delete(lstFolders[0]);



        //lblResult.Text = "Deleted ok.";



        //bindGrid(txtSearch.Text);



    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("FoldersEN.aspx");
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGridFolders;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind();
      
    }


    protected void trFolders_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (trFolders.SelectedValue != "")
            Response.Redirect("FoldersEN.aspx?ID=" + trFolders.SelectedValue);
    }
}
